/**
 * gislin 2017年7月11日
 */
package com.btcode.db.executer;

import com.btcode.db.config.DataBaseConfig;
import com.btcode.db.connection.IConnectionGetter;
import com.btcode.db.conver.DefaultValueConver;
import com.btcode.db.conver.IValueConver;
import com.btcode.db.result.PageResult;
import com.btcode.db.result.Row;
import com.btcode.db.sqlparameter.PageInfo;
import com.btcode.db.sqlparameter.SQLParameterList;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gislin 2017年7月11日
 */
public class PostgreSQLDataExecuter extends BaseDataExecuter {

    public PostgreSQLDataExecuter(DataBaseConfig config, IConnectionGetter connectionGetter) {
        super(config, connectionGetter);
    }

    @Override
    public PageResult queryListPage(String sql, SQLParameterList parms, PageInfo pageInfo) {

        String countSQL = " SELECT COUNT(*) FROM (" + sql + ") t ";
        Object countObj = queryScalar(countSQL, parms);

        IValueConver conver = new DefaultValueConver();
        int recordCount = conver.converToInteger(countObj);
        int pageCount = recordCount > 0?(int) Math.ceil(recordCount * 1.0 / pageInfo.getPageSize()):1;
        int pageIndex = pageInfo.getPageIndex() > pageCount ? pageCount : pageInfo.getPageIndex();
        int offset = (pageIndex - 1) * pageInfo.getPageSize();

        pageInfo.setPageCount(pageCount);
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setRecordCount(recordCount);

        String pageSql = sql + " limit  " +pageInfo.getPageSize()+ " offset " + offset;

        List<Row> rows = executeQuery(pageSql, parms);

        PageResult result = new PageResult(pageInfo, rows);

        return result;
    }

    /**
     * 对于character varying 类型 postgresql会获取多余补空的空格，给业务造成困扰，这里把其去掉
     */
    @Override
    protected List<Row> buildRows(ResultSet resultSet,boolean canScrollInsensitive) throws SQLException {
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        resultSet.last();
        List<Row> rows = new ArrayList<>(resultSet.getRow());
        resultSet.beforeFirst();

        while (resultSet.next()) {
            Row row = new Row();
            for (int i = 0; i < columnCount; i++) {
                Object value = resultSet.getObject(i + 1);
                if (value != null && value instanceof String) {
                    value = value.toString().trim();
                }
                row.put(metaData.getColumnName(i + 1).toUpperCase(), value);
            }
            rows.add(row);
        }

        return rows;
    }

}
